package com.example.tys.daggermvp.view.recyclerviewCompant.sticky;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.example.tys.daggermvp.utils.DisplayUtil;
import com.example.tys.daggermvp.view.recyclerviewCompant.BaseViewHolder;

/**
 * 支持LinearLayoutManager,GridLayoutManager。不支持{@link android.support.v7.widget.GridLayoutManager#setSpanCount(int)}
 * 请配合{@link StickyBaseAdapter}，{@link StickyBaseData}一起使用。
 *
 * @author tys
 * @date 2017/10/14
 */
public class StickyItemDivider<DataType extends StickyBaseData, VH extends BaseViewHolder> extends RecyclerView.ItemDecoration {

    private int titleTextColor = Color.GREEN;
    private int titleBackgroundColor = Color.GRAY;
    private int lineColor = Color.RED;
    private StickyBaseAdapter<DataType, VH> adapter;
    private Paint mPaint;
    private int mTitleHeight = (int) DisplayUtil.dp2px(35);
    private int mLineHeight = (int) DisplayUtil.dp2px(1);
    private int mSpanCount = 1;

    /**
     * 用于LinearLayoutManager时的构造函数
     *
     * @param adapter
     */
    public StickyItemDivider(@NonNull StickyBaseAdapter<DataType, VH> adapter) {
        this.adapter = adapter;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextSize(mTitleHeight * 0.5f);
    }

    /**
     * 用于GridLayoutManager的构造函数
     *
     * @param adapter
     * @param spanCount 每一行的列数,和GridLayoutManager{@link android.support.v7.widget.GridLayoutManager#mSpanCount}中的参数一致
     */
    public StickyItemDivider(@NonNull StickyBaseAdapter<DataType, VH> adapter, int spanCount) {
        this.adapter = adapter;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextSize(mTitleHeight * 0.5f);
        mSpanCount = spanCount;
    }

    /**
     * 计算 item间间隙(偏移)(是普通分割线 ,还是title)
     */
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
        DataType item = adapter.getData(position);
        Rect rect;
        if (position == 0) {
            rect = new Rect(0, mTitleHeight, 0, 0);
            item.setOffsetRect(rect);
        } else {
            //LinearLayoutManager
            if (mSpanCount == 1) {
                if (adapter.needTitle(position)) {
                    rect = new Rect(0, mTitleHeight, 0, 0);
                    item.setOffsetRect(rect);
                } else {
                    rect = new Rect(0, mLineHeight, 0, 0);
                    item.setOffsetRect(rect);
                }
            } else {
                //GridLayoutManager
                if (position % mSpanCount == 0 && adapter.needTitle(position)) {
                    rect = new Rect(0, mTitleHeight, 0, 0);
                    item.setOffsetRect(rect);
                } else {
                    if (position % mSpanCount == 0) {
                        rect = new Rect(0, mLineHeight, 0, 0);
                        item.setOffsetRect(rect);
                    } else {
                        rect = new Rect(adapter.getData(position - 1).getOffsetRect());
                        item.setOffsetRect(rect);
                    }
                }
            }
        }
        outRect.set(rect);
    }

    /**
     * 底层绘制,绘制分栏title
     */
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        int left = parent.getPaddingLeft();
        int right = parent.getMeasuredWidth() - parent.getPaddingRight();
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            int position = ((RecyclerView.LayoutParams) child.getLayoutParams()).getViewLayoutPosition();
            int bottom = child.getTop() - ((RecyclerView.LayoutParams) child.getLayoutParams()).topMargin;
            int top = bottom - mTitleHeight;
            if (position == 0) {
                drawTitle(c, position, left, top, right, bottom);
            } else {
                //LinearLayoutManager
                if (mSpanCount == 1) {
                    if (adapter.needTitle(position)) {
                        drawTitle(c, position, left, top, right, bottom);
                    } else {
                        top = bottom - mLineHeight;
                        drawDivision(c, left, top, right, bottom);
                    }
                } else {
                    //GridLayoutManager
                    if (position % mSpanCount == 0 && adapter.needTitle(position)) {
                        drawTitle(c, position, left, top, right, bottom);
                    } else {
                        if (position % mSpanCount == 0) {
                            //行首并且不需要显示title, 画行分割线
                            top = bottom - mLineHeight;
                            drawDivision(c, left, top, right, bottom);
                        } else {
                            //非行首，可能需要显示或者不需要显示title。经过数据填充后，肯定是不需要显示title
                            //ignore
                        }
                    }
                }
            }
        }
    }

    private void drawDivision(Canvas canva, int left, int top, int right, int bottom) {
        mPaint.setColor(lineColor);
        canva.drawRect(left, top, right, bottom, mPaint);
    }

    private void drawTitle(Canvas canvas, int position, int left, int top, int right, int bottom) {
        drawTitleBackground(canvas, left, top, right, bottom);
        drawText(canvas, adapter.getData(position).stickTitle(), left + mTitleHeight * 0.25f, bottom - mTitleHeight * 0.25f);
    }


    /**
     * 上层绘制,绘制顶部悬停title
     */
    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        int left = parent.getPaddingLeft();
        int right = parent.getMeasuredWidth() - parent.getPaddingRight();
        int top = parent.getPaddingTop();
        int bottom = top + mTitleHeight;
        mPaint.setColor(titleBackgroundColor);
        c.drawRect(left, top, right, bottom, mPaint);
        int pos = ((LinearLayoutManager) (parent.getLayoutManager())).findFirstVisibleItemPosition();
        if (pos != RecyclerView.NO_POSITION) {
            drawText(c, adapter.getData(pos).stickTitle(), left + mTitleHeight * 0.25f, bottom - mTitleHeight * 0.25f);
        }
    }

    private void drawText(Canvas c, String itemViewTitle, float x, float y) {
        if (!TextUtils.isEmpty(itemViewTitle)) {
            mPaint.setColor(titleTextColor);
            //mPaint.getTextBounds(itemViewTitle, 0, itemViewTitle.length(), mBounds);
            c.drawText(itemViewTitle, x, y, mPaint);
        }
    }

    private void drawTitleBackground(Canvas canva, int left, int top, int right, int bottom) {
        mPaint.setColor(titleBackgroundColor);
        canva.drawRect(left, top, right, bottom, mPaint);
    }

}
